package com.hpe.util;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.io.Serializable;
import java.util.List;

/**
 * Created by 李宇寒
 * 2017/9/20 0020 上午 11:59.
 */

public class HibernateUtil {

    private static SessionFactory sessionFactory;
    private static ThreadLocal session = new ThreadLocal();

    private HibernateUtil() {

    }

    static {

        Configuration cfg = new Configuration();
        cfg.configure();
        sessionFactory = cfg.buildSessionFactory();
    }

    public static Session getThreadLocalSession() {

        Session s = (Session) session.get();
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void closeSession() {
        Session s = (Session) session.get();
        if (s != null) {
            s.close();
            session.set(null);
        }
    }

    //    public static SessionFactory getSessionFactory() {
    //        return sessionFactory;
    //    }
    //
    //    public static Session getSession() {
    //        return sessionFactory.openSession();
    //    }

   //数据库操作方法

    /**
     * 插入数据
     * @param entity
     */
    public static void add(Object entity) {
        Session s = null;
        Transaction tx = null;
        try {
            s = HibernateUtil.getThreadLocalSession();
            tx = s.beginTransaction();

            s.save(entity);

            tx.commit();
        } finally {
            closeSession();
        }
    }

    /**
     * 更新数据
     * @param entity
     */
    public static void update(Object entity) {
        Session s = null;
        Transaction tx = null;
        try {
            s = HibernateUtil.getThreadLocalSession();
            tx = s.beginTransaction();
            s.update(entity);
            tx.commit();
        } finally {
            closeSession();
        }
    }

    /**
     * 根据条件更新数据
     * @param clazz
     * @param condition
     * @return
     */
    public static int update(String clazz,String condition) {
        Session s = null;
        Transaction tx = null;
        try {
            s = HibernateUtil.getThreadLocalSession();
            tx = s.beginTransaction();
            String hql="update "+clazz+" set "+condition;
            Query queryupdate=s.createQuery(hql);
            int result=queryupdate.executeUpdate();
            tx.commit();
            return result;
        } finally {
            closeSession();
        }
    }

    /**
     * 根据id查询，得到实体类对象
     * @param clazz
     * @param id
     * @return
     */
    public static Object get(Class clazz, Serializable id) {
        Session s = null;
        try {
            s = HibernateUtil.getThreadLocalSession();
            Object obj = s.get(clazz, id);
            return obj;
        } finally {
            closeSession();
        }
    }

    /**
     * 分页查询
     * @param clazz
     * @param condition
     * @param order
     * @param pageno
     * @param pagesize
     * @return
     */
    public static List query(String clazz, String condition, String order, int  pageno, int pagesize) {
        Session s = null;
        try {
            s =  HibernateUtil.getThreadLocalSession();;
            int startrecno=(pageno-1)*pagesize;
            String hql="from "+clazz+" "+condition+" "+order;
            Query query=s.createQuery(hql);
            query.setFirstResult(startrecno);
            query.setMaxResults(pagesize);
            return query.list();
        } finally {
            closeSession();
        }
    }

    /**
     * 带分页的多表联查
     * @param classes
     * @param fields
     * @param condition
     * @param pageno
     * @param pagesize
     * @return
     */
    public static List<Object[]> multiTableSelect(String[] fields,String[] classes, String condition,int  pageno, int pagesize){
        Session s = null;
        try{
            s = HibernateUtil.getThreadLocalSession();
            String classStr = "";
            String fieldStr = "";
            int startrecno=(pageno-1)*pagesize;
            for (int i=0;i<fields.length;i++){
                fieldStr += (fields[i]+",");
            }
            for (int i=0;i<classes.length;i++){
                classStr += (classes[i]+",");
            }
            fieldStr = fieldStr.substring(0,fieldStr.length()-1);
            classStr = classStr.substring(0,classStr.length()-1);
            String hql = "SELECT "+fieldStr+" FROM "+classStr+" "+condition;
            System.out.println(hql);
            Query query = s.createQuery(hql);
            query.setFirstResult(startrecno);
            query.setMaxResults(pagesize);
            return query.list();
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            closeSession();
        }
    }

    /**
     * 多表联查
     * @param classes
     * @param fields
     * @param condition
     * @return
     */
    public static List<Object[]> multiTableSelect( String[] fields,String[] classes,String condition){
        Session s = null;
        try{
            s = HibernateUtil.getThreadLocalSession();
            String classStr = "";
            String fieldStr = "";
            for (int i=0;i<fields.length;i++){
                fieldStr += (fields[i]+",");
            }
            for (int i=0;i<classes.length;i++){
                classStr += (classes[i]+",");
            }
            fieldStr = fieldStr.substring(0,fieldStr.length()-1);
            classStr = classStr.substring(0,classStr.length()-1);
            String hql ="SELECT "+fieldStr+" FROM "+classStr+" "+condition;
            System.out.println(hql);
            Query query = s.createQuery(hql);
            return query.list();
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            closeSession();
        }
    }

    /**
     * 查询
     * @param clazz
     * @param condition
     * @param order
     * @return
     */
    public static List query(String clazz,String condition,String order) {

        Session s = null;
        try {
            s =  HibernateUtil.getThreadLocalSession();;

            String hql="from "+clazz+" "+condition+" "+order;
            Query query=s.createQuery(hql);
            return query.list();

        } finally {
            closeSession();
        }
    }
    
    /**
     * 查询
     * @param hql
     * @return
     */
    public static List query(String hql) {

        Session s = null;
        try {
            s =  HibernateUtil.getThreadLocalSession();
            System.out.println(hql);
            Query query=s.createSQLQuery(hql);
            return query.list();

        } finally {
            closeSession();
        }
    }

    /**
     * 获得记录条数
     * @param clazz
     * @param condition
     * @return
     */
    public static int recordCount(String numcondition,String clazz,String condition) {

        Session s = null;
        try {
            s =  HibernateUtil.getThreadLocalSession();;

            String hql=" select count("+numcondition+") from "+clazz+" "+condition;
            Query query=s.createQuery(hql);
            return ((Long)query.uniqueResult()).intValue();

        } finally {
            closeSession();
        }
    }

    /**
     * 查询
     * @param clazz
     * @param condition
     * @return
     */
    public static List query(String clazz,String condition) {

        Session s = null;
        try {
            s =  HibernateUtil.getThreadLocalSession();;

            String hql="from "+clazz+" "+condition;
            Query query=s.createQuery(hql);
            return query.list();

        } finally {
            closeSession();
        }
    }

    /**
     * 查询部分数据
     * @param ClassName
     * @param fields
     * @param condition
     * @return
     */
    public static List<Object[]> selectFields(String ClassName, String[] fields,String condition){
        Session s = null;
        try{
            s = HibernateUtil.getThreadLocalSession();
            String temp = "";
            for (int i=0;i<fields.length;i++){
                temp += (fields[i]+",");
            }
            temp = temp.substring(0,temp.length()-1)+"";
            String hql = "SELECT "+temp+" FROM "+ClassName+" "+condition;
            System.out.println(hql);
            Query query = s.createQuery(hql);
            return query.list();
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            closeSession();
        }
    }

}

